package logic

import (
	"context"
	"fmt"
	"library/models/cache"
	"library/pkg"
	"math/rand"
	"strconv"
	"time"

	"library/libraryrpc/internal/svc"
	"library/libraryrpc/libraryrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *libraryrpc.SendSmsRequest) (*libraryrpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.RedisDB.Get(l.ctx, "sendSmsErr"+in.Mobile).Int()
	if result >= 1 {
		return nil, fmt.Errorf("一分钟只能发送一次")
	}
	intn := rand.Intn(9000) + 1000
	sms, err := pkg.SendSms(in.Mobile, strconv.Itoa(intn))
	if err != nil {
		return nil, err
	}
	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Message)
	}
	cache.RedisDB.Set(l.ctx, "sendSms"+in.Mobile, intn, time.Minute*5)
	incr := cache.RedisDB.Incr(l.ctx, "sendSmsErr"+in.Mobile)
	if incr.Val() == 1 {
		cache.RedisDB.Expire(l.ctx, "sendSmsErr"+in.Mobile, time.Minute*1)
	}
	return &libraryrpc.SendSmsResponse{}, nil
}
